import React from 'react';
import { Upload, Icon } from 'antd';
import { connect } from 'dva';

const imageOrigin = 'http://images.zxgvip.com/';
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

@connect(({ global }) => ({ token: global.uploadToken }))
class ImageUploader extends React.Component {
  constructor(props) {
    super(props);
    const { value } = props;
    const result = value ? `${imageOrigin}${value}` : '';
    this.state = {
      loading: false,
      imageUrl: result,
    };
  }

  handleChange = ({ file }) => {
    if (file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (file.status === 'done') {
      // Get this url from response in real world.
      getBase64(file.originFileObj, imageUrl =>
        this.setState({
          imageUrl,
          loading: false,
        })
      );
      const { onChange } = this.props;
      onChange(file.response.hash);
    }
  };

  beforeUpload = () => {
    const { dispatch } = this.props;
    return new Promise(async resolve => {
      await dispatch({ type: 'global/updateUploadToken' });
      resolve();
    });
  };

  render() {
    const { token } = this.props;
    const { loading, imageUrl } = this.state;
    const uploadButton = (
      <div>
        <Icon type={loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    return (
      <Upload
        listType="picture-card"
        showUploadList={false}
        action="https://up.qiniup.com"
        data={{ token }}
        beforeUpload={this.beforeUpload}
        onChange={this.handleChange}
      >
        {imageUrl ? <img style={{ height: '128px' }} src={imageUrl} alt="avatar" /> : uploadButton}
      </Upload>
    );
  }
}

export default ImageUploader;
